package com.plian.system.controller.pm.annualdonation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.FileTools;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.StringUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.entity.pm.annualdonationexecute.AnnualDonationExecute;
import com.plian.system.entity.pm.annualdonationexecutemain.AnnualDonationExecuteMain;
import com.plian.system.entity.pm.annualdonationrecord.AnnualDonationRecord;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pm.annualdonationexecutemain.IAnnualDonationExecuteMainService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.annualdonationexecutemain.AnnualDonationExecuteMainVO;
import com.plian.system.wrapper.pm.annualdonationexecutemain.AnnualDonationExecuteMainWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * 企业年度捐赠计划执行 控制器
 *
 * @author gangan
 * @since 2019-10-25
 */
@Api(value = "企业年度捐赠计划执行 控制器", tags = "企业年度捐赠计划执行接口")
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/annualdonationexecutemain")
public class AnnualDonationExecuteMainController extends BaseController {

    private IAnnualDonationExecuteMainService annualDonationExecuteMainService;

    private FormWorkflowService formWorkflowService;

    private AnnualDonationExecuteMainWrapper annualDonationExecuteMainWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "详情", notes = "传入annualDonationExecuteMain")
    public R<AnnualDonationExecuteMainVO> detail(@RequestBody AnnualDonationExecuteMain annualDonationExecuteMain) {
        AnnualDonationExecuteMainVO detail = annualDonationExecuteMainWrapper.entityToVO(annualDonationExecuteMainService.getOne(Condition.getQueryWrapper(annualDonationExecuteMain)));
        return annualDonationExecuteMainService.getDetailObj(detail);
    }

    /**
     * 分页 企业年度捐赠计划执行
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页", notes = "传入query")
    public ListResult<AnnualDonationExecuteMainVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<AnnualDonationExecuteMain> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new AnnualDonationExecuteMain()), entityList
        );
        TokenSearch<AnnualDonationExecuteMain> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);
        IPage<AnnualDonationExecuteMain> pages = annualDonationExecuteMainService.page(Condition.getPage(query), queryWrapper);
        List<AnnualDonationExecuteMainVO> annualDonationExecuteMainVOS = annualDonationExecuteMainWrapper.entityToVO(pages.getRecords());
        ListResult<AnnualDonationExecuteMainVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(annualDonationExecuteMainVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 新增或修改 企业年度捐赠计划执行
     */
    @PostMapping("/submit")
    @LogOperation("企业年度捐赠计划执行-提交")
    @Resubmit(delaySeconds = 0)
    @ApiOperation(value = "新增或修改", notes = "传入annualDonationExecuteMain")
    public R submit(@Valid @RequestBody AnnualDonationExecuteMain annualDonationExecuteMain) {
        if (annualDonationExecuteMain.getVersion() == null) {
            annualDonationExecuteMain.setVersion("1");
        }
        String checkResult = annualDonationExecuteMainService.checkIsExisted(annualDonationExecuteMain.getId(), annualDonationExecuteMain.getCode(), annualDonationExecuteMain.getFilingCode());
        if (!StringUtil.isEmpty(checkResult)) {
            return new R(CustomCode.builder().message(checkResult).code(1999).success(false).build());
        }
        boolean result = annualDonationExecuteMainService.submit(annualDonationExecuteMain);
        HashMap<String, Object> processVariable = new HashMap<>();
        Double amount = 0d;
        if (annualDonationExecuteMain != null && annualDonationExecuteMain.getAnnualDonationExecutes() != null && annualDonationExecuteMain.getAnnualDonationExecutes().size() > 0) {
            List<AnnualDonationExecute> records = annualDonationExecuteMain.getAnnualDonationExecutes();
            for (AnnualDonationExecute record : records) {
                if (record != null && record.getDonationAmount() != null) {
                    amount += record.getDonationAmount().doubleValue();
                }
            }

        }
        processVariable.put("juanzengjine", amount * 10000);
        if (annualDonationExecuteMainService.checkJzjh(annualDonationExecuteMain.getId())) {//为了不改流程图就判断为true就复制50000以上
            processVariable.put("juanzengjine", 500000);
        } else {
            processVariable.put("juanzengjine", 0);
        }
        formWorkflowService.startProcessAndSimulate(String.valueOf(annualDonationExecuteMain.getId()), annualDonationExecuteMain.getFormType(), processVariable);

        return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 删除 企业年度捐赠计划执行
     */
    @PostMapping("/remove")
    @LogOperation("企业年度捐赠计划执行-删除")
    @ApiOperation(value = "删除", notes = "传入pd")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return annualDonationExecuteMainService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 生成年度不良资产 年度不良资产核销主表
     */
    @PostMapping("/initialization")
    @ApiOperation(value = "生成年度不良资产", notes = "传入reportCompanyId和year")
    public R<AnnualDonationExecuteMainVO> initialization(@RequestParam String reportCompanyId, @RequestParam String year) {
        String result = annualDonationExecuteMainService.initialization(reportCompanyId, year);
        if (result != null && !"不存在已审的年度计划数据".equals(result) && !"已存在初始化数据，请不要多次初始化".equals(result)
                && !"初始化失败".equals(result)) {
            AnnualDonationExecuteMainVO detail = annualDonationExecuteMainWrapper.entityToVO(annualDonationExecuteMainService.getById(result));
            return annualDonationExecuteMainService.getDetailObj(detail);
        } else {
            return new R(CustomCode.builder().message(result).code(1999).success(false).build());
        }
    }

    /**
     * 取子表数据（更新）
     */
    @PostMapping("/changeall")
    @ApiOperation(value = "取子表数据（更新）", notes = "传入id")
    public R<AnnualDonationExecuteMainVO> changeAll(@RequestParam Long id) {
        annualDonationExecuteMainService.changeAll(id);
        AnnualDonationExecuteMainVO detail = annualDonationExecuteMainWrapper.entityToVO(annualDonationExecuteMainService.getById(id));
        detail = annualDonationExecuteMainService.setChild(detail);
        return annualDonationExecuteMainService.getDetailObj(detail);
    }

    /**
     * 打印
     */
    @GetMapping("/buildpdf/{id}")
    @ApiOperation(value = "打印", notes = "传入id")
//	@PassToken
    public ResponseEntity<FileSystemResource> buildPdf(@PathVariable Long id) {
        return FileTools.exportPdf(annualDonationExecuteMainService.createReceptFile(id));
    }

    /**
     * 下载doc
     */
    @GetMapping("/buildword/{id}")
    @ApiOperation(value = "下载doc", notes = "传入id")
//	@PassToken
    public void buildword(@PathVariable Long id, HttpServletResponse response) {
        File buildword = annualDonationExecuteMainService.buildword(id, response);
        String fileName = "";
        try {
            fileName = buildword.getName();
            //fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            InputStream inputStream = new FileInputStream(buildword);
            // 激活下载操作
            OutputStream os = response.getOutputStream();
            // 循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            // 这里主要关闭。
            os.close();
            inputStream.close();
        } catch (UnsupportedEncodingException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        } catch (FileNotFoundException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        } catch (IOException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }
}
